<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>定时关机管理</title>
    <style>
        .container { max-width: 800px; margin: 20px auto; padding: 20px; }
        .form-section { margin-bottom: 30px; border: 1px solid #ddd; padding: 15px; }
        .error { color: red; margin-top: 5px; }
        .log { color: green; margin-top: 5px; }
        .schedule-list { margin-top: 20px; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 8px; border: 1px solid #ddd; text-align: left; }
        .time-input { margin: 10px 0; }
        .status-active { color: green; }
        .status-completed { color: gray; }
        .status-canceled { color: red; }
        .status-expired { color: orange; }
    </style>
</head>
<body>
    <div class="container">
        <h1>定时关机管理</h1>
        
        <!-- 添加计划表单 -->
        <div class="form-section">
            <h2>添加关机计划</h2>
            <form id="shutdownForm">
                <div>
                    <label>计划类型:</label>
                    <select id="scheduleType" onchange="toggleScheduleType()">
                        <option value="once">单次执行</option>
                        <option value="daily">每日重复</option>
                    </select>
                </div>
                <div class="time-input" id="timeSelection">
                    <label>执行时间:</label>
                    <input type="datetime-local" id="scheduleTime" required>
                </div>
                <div>
                    <label>延迟分钟数:</label>
                    <input type="number" id="delayMinutes" min="1" value="5">
                </div>
                <div>
                    <label><input type="checkbox" id="forceShutdown"> 强制关机</label>
                </div>
                <button type="submit">添加计划</button>
                <div class="error" id="shutdownError"></div>
                <div class="log" id="shutdownLog"></div>
            </form>
        </div>

        <!-- 计划列表 -->
        <div class="schedule-list">
            <h2>当前计划</h2>
            <button onclick="loadSchedules()">刷新列表</button>
            <table id="scheduleTable">
                <thead>
                    <tr>
                        <th>类型</th>
                        <th>计划时间</th>
                        <th>参数</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>

    <script>
        // 初始化时间输入
        function toggleScheduleType() {
            const type = document.getElementById('scheduleType').value;
            const container = document.getElementById('timeSelection');
            container.innerHTML = `
                <label>执行时间:</label>
                <input type="${type === 'daily' ? 'time' : 'datetime-local'}" 
                     id="scheduleTime" required>
            `;
        }

        // 加载计划
        document.addEventListener('DOMContentLoaded', loadSchedules);

        async function loadSchedules() {
            try {
                const response = await fetch('/api/schedules');
                const schedules = await response.json();
                renderSchedules(schedules);
            } catch (error) {
                showError('shutdownError', '加载失败: ' + error.message);
            }
        }

        function renderSchedules(schedules) {
            const tbody = document.querySelector('#scheduleTable tbody');
            tbody.innerHTML = schedules.map(schedule => `
                <tr>
                    <td>${schedule.type === 'daily' ? '每日' : '单次'}</td>
                    <td>${schedule.type === 'daily' ? 
                        schedule.time : 
                        new Date(schedule.time).toLocaleString()}</td>
                    <td>${JSON.stringify(schedule.params)}</td>
                    <td class="status-${schedule.status}">${getStatusText(schedule.status)}</td>
                    <td>
                        <button onclick="deleteSchedule('${schedule.id}')">删除</button>
                    </td>
                </tr>
            `).join('');
        }

        function getStatusText(status) {
            const statusMap = {
                active: '等待执行',
                completed: '已完成',
                canceled: '已取消',
                expired: '已过期'
            };
            return statusMap[status] || '未知状态';
        }

        // 提交表单
        document.getElementById('shutdownForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const schedule = {
                type: document.getElementById('scheduleType').value,
                time: document.getElementById('scheduleTime').value,
                delay: parseInt(document.getElementById('delayMinutes').value),
                force: document.getElementById('forceShutdown').checked
            };

            // 前端验证
            if (!validateSchedule(schedule)) {
                return;
            }

            try {
                const response = await fetch('/api/shutdown', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(schedule)
                });
                
                if (!response.ok) throw new Error(await response.text());
                showLog('shutdownLog', '计划添加成功');
                loadSchedules();
            } catch (error) {
                showError('shutdownError', error.message);
            }
        });

        function validateSchedule(schedule) {
            const now = new Date();
            if (schedule.type === 'once') {
                const scheduleTime = new Date(schedule.time);
                if (isNaN(scheduleTime.getTime()) || scheduleTime <= now) {
                    showError('shutdownError', '单次计划时间必须是有效的未来时间');
                    return false;
                }
            } else if (schedule.type === 'daily') {
                if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(schedule.time)) {
                    showError('shutdownError', '每日计划时间格式必须为 HH:MM');
                    return false;
                }
            }
            return true;
        }

        // 删除计划
        async function deleteSchedule(id) {
            if (!confirm('确定删除该计划？')) return;
            
            try {
                const response = await fetch(`/api/schedules/${id}`, {
                    method: 'DELETE'
                });
                
                if (!response.ok) throw new Error(await response.text());
                showLog('shutdownLog', '计划删除成功');
                loadSchedules();
            } catch (error) {
                showError('shutdownError', '删除失败: ' + error.message);
            }
        }

        function showError(elementId, message) {
            const el = document.getElementById(elementId);
            el.textContent = message;
            setTimeout(() => el.textContent = '', 5000);
        }

        function showLog(elementId, message) {
            const el = document.getElementById(elementId);
            el.textContent = message;
            setTimeout(() => el.textContent = '', 5000);
        }
    </script>
</body>
</html>